<script setup lang="ts">
import { ref } from 'vue'
import * as accountApi from '@/api/account'
import * as cardCouponsApi from '@/api/cardCoupons'
import * as fishApi from '@/api/fishGoods'
import { message } from 'ant-design-vue'
import type { SelectProps } from 'ant-design-vue'

const myModal = ref()

const showModal = (id: string, userId: string) => {
  getRobatList()
  formState.value.id = id
  formState.value.userId = userId
  myModal.value?.showModal()
}

//#region 拉取机器人列表
let okRobat = ref<string>()
const robatList = ref<SelectProps['options']>([])
interface OptionList {
  label: string
  value: string
}
let optionList = ref<Array<OptionList>>([])
const getRobatList = async () => {
  const params = {
    currentPage: 1,
    pageSize: 100,
  }
  try {
    let { state, data, message: msg } = await accountApi.getFishRobotList(params)
    if (state === 200) {
      robatList.value = data.list
      optionList.value = data.list.map((item: any) => {
        return {
          label: item.nickName,
          value: item.id,
        }
      })
      if (data.list.length == 0) {
        message.error('闲鱼：无平台账号，请先添加平台账号')
      } else if (data.list.length > 0) {
        selectRobat(data.list[0].id)
      }
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}
const selectRobat = (selectValue: unknown) => {
  productList.value = []
  okRobat.value = selectValue as string
  console.log('okRobat=', okRobat.value)
  getProductList(okRobat.value)
}
//#endregion 拉取机器人列表

//#region 获取商品列表
let searchTitle = ref('')
let hasNextPageFlag = ref(false)
let page = ref(1)
const productList = ref<SelectProps['options']>([])
const getProductList = async (robotId: string) => {
  try {
    let {
      state,
      data,
      message: msg,
    } = await cardCouponsApi.cardFishProductList({
      currentPage: page.value,
      pageSize: 100,
      robotId,
      title: searchTitle.value,
    })
    if (state === 200) {
      hasNextPageFlag.value = data.hasNext
      productList.value = data.list.map((item: any) => {
        return {
          label: item.title,
          value: item.itemId,
        }
      })
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}
//#endregion 获取商品列表

// 商品列表 - 加载更多
const getMore = () => {
  // if (hasNextPageFlag.value) {
  //   page.value++
  //   getProductList(okRobat.value as string)
  // }
}

const emit = defineEmits<{
  refresh: []
}>()

defineExpose({
  showModal,
})

const formRef = ref()
let labelCol = {
  style: {
    // width: '120px',
  },
}
interface FormState {
  id?: number | string
  toRobot?: number | string
  userId?: number | string
}
const formState = ref<FormState>({})

let loading = ref<boolean>(false)

const handleOk = async () => {
  loading.value = true
  const params = {
    couponId: formState.value.id,
    itemIdList: okProduct.value,
    couponType: 1, // 1：星驰，2：91卡券
    couponUserId: formState.value.userId,
  }
  try {
    const { state, message: msg } = await cardCouponsApi.cardRollRelevanceFishProduct(params)
    if (state === 200) {
      message.success('关联成功')
      handleCancel()
      emit('refresh')
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
  loading.value = false
}

const handleCancel = () => {
  myModal.value?.cancelModal()
  formRef.value.resetFields()
}

// select搜索
const filterOption = (input: string, option: any) => {
  return option.label.indexOf(input) >= 0
}

let okProduct = ref<Array<string>>()
const selectProduct = (selectValue: any) => {
  okProduct.value = selectValue
  console.log('okProduct=', okProduct.value)
  handleSearch('')
}

let syncProductFlag = ref(false)
// 同步商品
const syncProduct = async () => {
  syncProductFlag.value = true
  setTimeout(() => {
    syncProductFlag.value = false
  }, 1000 * 60)
  // console.log('同步商品okRobat=', okRobat.value) // 同步这个平台账号的商品
  let parmas = {
    robotId: okRobat.value,
  }
  try {
    let { state, data, message: msg } = await fishApi.synchronizationProduct(parmas)
    if (state === 200) {
      message.success({
        content: '提交同步商品任务成功，请您稍等1-2分钟后刷新查看！',
        duration: 5,
      })
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}

// 下拉的模糊搜索
const debounce = (func: Function, wait: number) => {
  let timeout: ReturnType<typeof setTimeout> | null = null
  return (...args: any[]) => {
    console.log('args=', args)
    const later = () => {
      timeout = null
      func.apply(null, args)
    }
    if (timeout) clearTimeout(timeout)
    timeout = setTimeout(later, wait)
  }
}

const handleSearch = (val: string) => {
  console.log('搜索值:', val)
  searchTitle.value = val
  getProductList(okRobat.value as string)
}

const debounceSearch = debounce(handleSearch, 500)
</script>

<template>
  <MyModal ref="myModal" title="关联商品" :top="35">
    <template #content>
      <div style="display: grid; place-items: center">
        <a-form ref="formRef" :model="formState" :label-col="labelCol">
          <a-form-item label="平台账号" name="robotId">
            <a-select
              v-model:value="okRobat"
              @change="selectRobat"
              placeholder="请选择"
              style="width: 280px"
              show-search
              :options="optionList"
              :filter-option="filterOption"
            >
              <a-select-option v-for="(item, index) in optionList" :key="index" :value="item.value">
                {{ item.label }}
              </a-select-option>
            </a-select>
          </a-form-item>

          <a-form-item label="关联商品" name="toRobot">
            <a-select
              v-model:value="formState.toRobot"
              placeholder="请选择"
              mode="multiple"
              allowClear
              style="width: 280px"
              show-search
              :options="productList"
              :filter-option="false"
              optionFilterProp="label"
              @change="selectProduct"
              @popupScroll="getMore"
              @search="debounceSearch"
            >
              <!-- <a-select-option v-for="(item, index) in productList" :key="item" :value="item.value">
                {{ item }}
              </a-select-option> -->
            </a-select>
            <a-tooltip placement="top">
              <template #title>同步商品（每次同步时间间隔为60秒）</template>
              <a-button type="link" @click="syncProduct" :disabled="syncProductFlag">
                <template #icon>
                  <SyncOutlined />
                </template>
              </a-button>
            </a-tooltip>
          </a-form-item>

          <a-form-item style="text-align: right">
            <a-space>
              <a-button @click="handleCancel">取消</a-button>
              <a-button type="primary" :loading="loading" @click="handleOk">确定关联</a-button>
            </a-space>
          </a-form-item>
        </a-form>
      </div>
    </template>
  </MyModal>
</template>
